
const router = require('koa-router')()

router.prefix('/guide')

//newsimg
//页面初始化时获取数据库内的数据条目
router.get('/get', async (ctx, next) => {
  let sql = 'SELECT * FROM guide WHERE isrotograph = 1 ORDER BY guideid'
  let result = await ctx.db.EXCUTE(sql);
  console.log(result);
  ctx.body = {
    code: 200,
    data: result
  }
})
router.post('/addread', async (ctx, next) => {
  let guideid = ctx.request.body.guideid;
  let sql = 'SELECT readnum FROM guide WHERE guideid = ? ';
  let num = await ctx.db.EXCUTE(sql, [guideid]);
  console.log(num[0].readnum);
  let num1 = num[0].readnum + 1;
  let sql1 = 'UPDATE guide SET readnum=? WHERE guideid=?';
  await ctx.db.EXCUTE(sql1, [num1, guideid]);
  ctx.body = {
    code: 200,
  }
})

router.post('/collectarr', async (ctx, next) => {
  let arr = [];
  let userid = ctx.request.body.userid;
  // console.log(userid);
  let sql = 'SELECT guideid FROM collect WHERE userid = ? ';
  let result = await ctx.db.EXCUTE(sql, [userid]);
  for (let i = 0; i < result.length; i++) {
    arr.push(result[i].guideid);
  }
  // console.log(arr);
  ctx.body = {
    code: 200,
    data: arr
  }
})

router.post('/selectplant', async (ctx, next) => {
  let cropname = ctx.request.body.cropname;
  let sql = 'SELECT * FROM tags,growtime WHERE tags.cropname = ? and tags.cropsid = growtime.cropsid and growtime.grownum = 1 ';
  let result = await ctx.db.EXCUTE(sql, [cropname]);
  let sql1 = 'SELECT * FROM plantswiper WHERE cropname = ?'
  let result1 = await ctx.db.EXCUTE(sql1, [cropname]);
  console.log(result[0], result1);
  if (result[0]) {
    ctx.body = {
      code: 200,
      data: result[0],
      imgs: result1
    }
  }
  else {
    ctx.body = {
      code: 500,
    }
  }
})

router.post('/planttips', async (ctx, next) => {
  let cropsid = ctx.request.body.cropsid;
  let result = await ctx.db.EXCUTE("SELECT * FROM growtip WHERE cropsid=?", [cropsid]);
  console.log(result);
  if (result[0]) {
    ctx.body = {
      code: 200,
      data: result,
    }
  } else {
    ctx.body = {
      code: 500,
    }
  }
})

router.post('/plantnews', async (ctx, next) => {
  let title = ctx.request.body.title;
  let result = await ctx.db.EXCUTE("SELECT * FROM guide WHERE title LIKE '%" + title + "%'");
  console.log(result);
  if (result[0]) {
    ctx.body = {
      code: 200,
      data: result,
    }
  } else {
    ctx.body = {
      code: 500,
    }
  }
})

module.exports = router
